<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\api\service\Token;
use app\api\model\Pets as PetsModel;
use app\api\model\PetsCollect;
use app\api\model\Feed;
use think\Db;

class Pets extends Api
{
    /**
     * 宠物展示
     * @return [type] [description]
     */
    public function index()
    {
        $pets['all'] = model('Pets')->field('id, avatar')->where(['status' => 1])->limit(6)->select();
        $pets['dog'] = model('Pets')->field('id, avatar')->where(['status' => 1, 'type_id' => 1])->limit(6)->select();
        $pets['cat'] = model('Pets')->field('id, avatar')->where(['status' => 1, 'type_id' => 0])->limit(6)->select();
        return $pets;
    }

    public function rand($type) {
        $config =  config('database');
        $tablePets = $config['prefix'] . 'pets';
        if($type == 3) {
            $where = 'status = 1';
        }else{
            $where = 'status = 1 AND type_id=' . $type;
        }
        $res = Db::query("SELECT
                	*
                FROM
                	$tablePets
                WHERE $where
                ORDER BY
                	rand()
                LIMIT 0,
                 6");
        return $res;
    }
    /**
     * 搜索宠物
     * @param  [type] $key [description]
     * @return [type]      [description]
     */
    public function search($key)
    {
        $pets = PetsModel::with('user')->field('id,uid,name,avatar')->where(['id' => $key])->whereOr('name','like',"%$key%")->select();
        $re = [];
        if(!empty($pets)) {
            foreach ($pets as $k => $v) {
                $re[$k]['name'] = $v['name'];
                $re[$k]['pets_id'] = $v['id'];
                $re[$k]['avatar'] = $v['avatar'];
                $re[$k]['master_id'] = msubstr($v->user->nickname, 0, 7);
            }
        }
        return $re;
    }

    public function info($id)
    {
        $res = [];
        $pets = model('Pets')->where(['id' => $id])->find();
        $pets['type'] = PetsModel::getTypeArr($pets['type_id']);
        $pets['jueyu'] = $pets['sterilization'] ? '是' : '否';
        $pets['age'] = birthday($pets['birthday']);
        if(!$pets) {
            return [
                'code' => 0,
                'error' => '没有找到数据！'
            ];
        }
        unset($pets['status']);
        unset($pets['create_time']);
        unset($pets['type_id']);
        unset($pets['birthday']);
        $res['info'] = $pets;
        $res['info']['nextGrowth'] = getNextGrowthValue($pets['id']);
        // 收藏
        $uid = Token::getCurrentUid();
        if($pets['uid'] == $uid) {
            $res['self'] = true;
        }else{
            $res['self'] = false;
        }
        $collect = model('PetsCollect')->where(['uid' => $uid, 'pets_id' => $id])->find();
        $res['collect'] = $collect ? 1 : 0;
        $res['feedTotal'] = ($pets['growth'] / $res['info']['nextGrowth']) * 100;
        $config =  config('database');
        $tableFeed = $config['prefix'] . 'feed';
        $tableUser = $config['prefix'] . 'user';
        $tablePets = $config['prefix'] . 'pets';
        $tablePetsPhoto = $config['prefix'] . 'pets_photo';
        $tablePetsPhotoId = $config['prefix'] . 'pets_photo_id';

        // 宠物皮肤选择
        $res['skin'] = getPetsGrowthGroup($id);

        // $photo = model('PetsPhoto')->field('img')->where(['pets_id' => $id])->limit(3)->order('id desc')->select();
        $photo = Db::query("SELECT
                    	pi.pets_id,
                    	pp.uid,
                    	pp.id,
                    	pp.img,
                        pp.type
                    FROM
                    	$tablePetsPhotoId AS pi
                    JOIN $tablePetsPhoto AS pp ON pi.`photo_id` = pp.`id`
                    WHERE
	                pi.pets_id = $id
                    ORDER BY
                    pp.id DESC
                    LIMIT 3");
        $res['feedData'] = $this->feedData($id);

        // 收藏数
        $res['collectNum'] = db('PetsCollect')->where(['pets_id' => $id])->count();
        $res['photo'] = $photo;
        return $res;
    }

    public function skin($pets_id, $id) {
        $level = db('PetsLevel')->where(['id' => $id])->find();
        if(!$level) {
            return ['status' => 0, 'error' => '非法操作！'];
        }
        $res = model('Pets')->save(['skin' => $level['color']], ['id' => $pets_id]);
        if($res) {
            return ['status' => 1, 'msg' => '操作成功！', 'color' => $level['color']];
        }else{
            return ['status' => 0, 'error' => '操作失败！'];
        }
    }

    /**
     * 宠物投喂数据
     * @param  [type]  $pets_id [description]
     * @param  integer $page    [description]
     * @param  integer $size    [description]
     * @return [type]           [description]
     */
    public function feedData($pets_id, $page = 1, $size = 3) {
        $pageIndex = $page - 1;
        $config =  config('database');
        $tableFeed = $config['prefix'] . 'feed';
        $tableUser = $config['prefix'] . 'user';
        $data = Db::query("SELECT
                        	sum(f.`feed_num`) AS feed_total,
                        	f.`uid`,
                        	f.`pets_id`,
                        	u.`nickname`,
                        	u.`avatar`
                        FROM
                        	$tableFeed AS f
                        LEFT JOIN $tableUser AS u ON f.`uid` = u.id
                        WHERE
                        	`pets_id` = $pets_id
                        GROUP BY
                        	`uid`
                        ORDER BY
                        	`feed_total` DESC
                        limit $pageIndex,$size");
        $list = $data;
        if($data) {
            foreach ($data as $k => $v) {
                $list[$k]['pets_num'] = counUserPets($v['uid']);
                $list[$k]['nickname'] = msubstr($v['nickname'], 0, 5);
            }
        }
        return $list;
    }

    public function getPetsList() {
        $uid = Token::getCurrentUid();
        $pets = model('Pets')->where(['uid' => $uid])->order('id desc')->select();
        $re = [];
        if($pets) {
            foreach ($pets as $k => $v) {
                $re[$k]['id']     = $v['id'];
                $re[$k]['name']   = $v['name'];
                $re[$k]['avatar'] = $v['avatar'];
                $re[$k]['sex']    = $v['sex'];
                $re[$k]['jueyu']  = $v['sterilization'] ? '是' : '否';
                $re[$k]['info']   = $v['info'];
                $re[$k]['type']   = PetsModel::getTypeArr($v['type_id']);
                $re[$k]['age']    = birthday($v['birthday']);
            }
        }
        return $re;
    }

    /**
     * 今日排行榜
     * @return [type] [description]
     */
    public function todayRank() {
        $rank = [];
        $config =  config('database');
        $begintime = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endtime = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $tableFeed = $config['prefix'] . 'feed';
        $tablePets = $config['prefix'] . 'pets';
        $tableCollect = $config['prefix'] . 'pets_collect';
        $feedData = Db::query("SELECT
                	sum(f.feed_num) AS feed_num,
                    f.pets_id,
                	p.name,
                	p.avatar
                FROM
                	$tableFeed AS f
                LEFT JOIN $tablePets AS p ON f.pets_id = p.id
                WHERE
                	feed_time > $begintime
                AND feed_time < $endtime
                GROUP BY
                    f.pets_id
                ORDER BY
                	feed_num DESC
                LIMIT 5");
        if($feedData) {
            $rank['feed'] = $feedData;
        }else{
            $rank['feed'] = [];
        }
        $collectData = Db::query("SELECT
                        	count(c.id) AS collect_num,
                            c.pets_id,
                        	p.name,
                        	p.avatar
                        FROM
                        	$tableCollect AS c
                        JOIN $tablePets AS p ON c.pets_id = p.id
                        WHERE
                        	time > $begintime
                        AND time < $endtime
                        GROUP BY
                          c.pets_id
                        ORDER BY
                        	collect_num DESC
                        LIMIT 5");
        if($collectData) {
            $rank['collect'] = $collectData;
        }else{
            $rank['collect'] = [];
        }
        return $rank;
    }

    public function create()
    {
        $data = input('post.');
        $uid = Token::getCurrentUid();
        $num = model('Pets')->where(['uid' => $uid])->count();
        if($num >= 10) {
            return ['code' => 0, 'error' => '您最多可以创建10个宠物'];
        }
        $pets = PetsModel::create(
            [
                'uid' => $uid,
                'name' => $data['name'],
                'avatar' => $data['avatar'],
                'type_id' => $data['type'],
                'sex' => $data['sex'],
                'sterilization' => $data['sterilization'],
                'birthday' => $data['birthday'],
                'info' => $data['info'],
                'create_time' => time()
            ]);
        return ['code' => 1, 'id' => $pets->id];
    }

    public function petsinfo($id) {
        $uid = Token::getCurrentUid();
        $pets = model('Pets')->where(['id' => $id, 'uid' => $uid])->find();
        return $pets;
    }

    public function edit($id) {
        $post = input('post.');
        $uid = Token::getCurrentUid();
        $pets = model('Pets')->where(['id' => $id])->find();
        if($pets['uid'] !== $uid) {
            return ['code' => 0, 'error' => '您没有权限！'];
        }
        $data = [
            'name' => $post['name'],
            'avatar' => $post['avatar'],
            'type_id' => $post['type'],
            'sex' => $post['sex'],
            'sterilization' => $post['sterilization'],
            'birthday' => $post['birthday'],
            'info' => $post['info'],
            'status' => 0
        ];
        $res = model('Pets')->save($data, ['id' => $id]);
        if($res) {
            return ['code' => 1, 'info' => '修改成功！'];
        }else{
            return ['code' => 0, 'error' => '修改失败！'];
        }
    }

    /**
     * 喂食
     * @return [type] [description]
     */
    public function feed($pets_id)
    {
       $uid = Token::getCurrentUid();
       $begintime = mktime(0,0,0,date('m'),date('d'),date('Y'));
       $endtime = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
       $feed_log = model('Feed')->where('feed_time','between',[$begintime, $endtime])->where(['uid' => $uid, 'pets_id' => $pets_id])->find();
       if($feed_log) {
           return [
               'code' => 0,
               'error' => '您今天已经投喂过了'
           ];
       }
       $data = [
           'uid' => $uid,
           'pets_id' => $pets_id,
           'feed_num' => 1,
           'feed_time' => time()
       ];
       $feed = model('Feed')->insert($data);
       $re = [];
       if($feed) {
           model('Pets')->where(['id' => $pets_id])->setInc('growth');
           return [
               'code' => 1,
               'info' => '喂食成功！'
           ];
       }else{
           return [
               'code' => 0,
               'error' => '喂食失败！'
           ];
       }
    }

    /**
     * 收藏榜
     * @return [type] [description]
     */
    public function collectRank($page = 1, $size = 10)
    {
        $page = $page - 1;
        $rank = Db::query("SELECT
            	pets_id,
            	count(spc.`id`) AS collect_num,
            	sp.name,
            	sp.avatar
            FROM
            	sent_pets_collect AS spc
            JOIN sent_pets AS sp ON spc.pets_id = sp.id
            GROUP BY
            	pets_id
            ORDER BY
            	collect_num DESC
            LIMIT $page,$size");
        return ['code' => 1, 'data' => $rank];
    }

    /**
     * 投喂榜
     * @return [type] [description]
     */
    public function feedRank($page = 1, $size = 10)
    {
        $page = $page - 1;
        $rank = Db::query("SELECT
        	pets_id,
        	sum(`feed_num`) AS feed_total,
        	sp.name,
        	sp.avatar
        FROM
        	sent_feed AS sf
        JOIN sent_pets AS sp ON sf.pets_id = sp.id
        GROUP BY
        	pets_id
        ORDER BY
        	feed_total DESC
        LIMIT $page,$size");
        return ['code' => 1, 'data' => $rank];
    }

    public function collect($pets_id)
    {
        $uid = Token::getCurrentUid();
        $data = [
            'uid' => $uid,
            'pets_id' => $pets_id,
            'time' => time()
        ];
        $collect = model('PetsCollect')->insert($data);
        $res = [];
        if($collect) {
            $res = [
                'code' => 1,
                'info' => '收藏成功！'
            ];
        }else{
            $res = [
                'code' => 0,
                'error' => '操作失败！'
            ];
        }
        return $res;
    }

    public function mycollect($page=1, $size = 20)
    {
        $uid = Token::getCurrentUid();
        $collect = PetsCollect::with('pets')->order('time desc')->where(['uid' => $uid])->paginate($size, true, ['page' => $page]);
        if ($collect->isEmpty())
        {
            return [
                'current_page' => $collect->currentPage(),
                'data' => []
            ];
        }else{
            $data = $collect->toArray();
            $re = [];
            foreach ($data['data'] as $k => $v) {
                $re[$k]['id']     = $v['pets_id'];
                $re[$k]['name']   = $v['pets']['name'];
                $re[$k]['avatar'] = $v['pets']['avatar'];
                $re[$k]['sex']    = $v['pets']['sex'];
                $re[$k]['jueyu']  = $v['pets']['sterilization'] ? '是' : '否';
                $re[$k]['info']   = $v['pets']['info'];
                $re[$k]['type']   = PetsModel::getTypeArr($v['pets']['type_id']);
                $re[$k]['age']    = birthday($v['pets']['birthday']);
            }
            return [
                'current_page' => $collect->currentPage(),
                'data' => $re
            ];
        }
    }

    public function cancelcollect($pets_id)
    {
        $uid = Token::getCurrentUid();
        $where = [
            'uid' => $uid,
            'pets_id' => $pets_id,
        ];
        $collect = model('PetsCollect')->where($where)->delete();
        $res = [];
        if($collect) {
            $res = [
                'code' => 1,
                'info' => '取消收藏成功！'
            ];
        }else{
            $res = [
                'code' => 0,
                'error' => '操作失败！'
            ];
        }
        return $res;
    }
}
